<template>
  <div class="page-container workflow-instance-editor-page">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="handleCancel" text>
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>创建工作流实例</h2>
      </div>
    </div>

    <el-card class="basic-info-card">
      <el-form :model="instanceInfo" label-width="120px" :inline="true">
        <el-form-item label="实例名称">
          <el-input
            v-model="instanceInfo.instance_name"
            disabled
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="模板名称">
          <el-input
            v-model="instanceInfo.template_name"
            disabled
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item label="触发人">
          <el-input
            v-model="instanceInfo.trigger_user"
            disabled
            style="width: 300px"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="editor-card">
      <WorkflowEditor
        ref="editorRef"
        v-model="workflowData"
        save-button-text="发布"
        @save="handleSaveInstance"
      />
    </el-card>

    <!-- 调度类型选择对话框 -->
    <el-dialog
      v-model="scheduleDialogVisible"
      title="选择调度类型"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="调度类型" required>
          <el-radio-group v-model="scheduleForm.schedule_type" @change="handleScheduleTypeChange">
            <el-radio value="manual">立即执行</el-radio>
            <el-radio value="create_only">仅创建</el-radio>
            <el-radio value="scheduled">定时执行（一次性）</el-radio>
            <el-radio value="dependent">依赖执行</el-radio>
          </el-radio-group>
          <div class="form-tip" style="margin-top: 8px;">
            <span v-if="scheduleForm.schedule_type === 'manual'">
              创建后实例将自动进入执行队列（约1分钟内开始执行）
            </span>
            <span v-else-if="scheduleForm.schedule_type === 'create_only'">
              创建后实例状态为"未运行"，需要手动点击"运行"按钮启动
            </span>
            <span v-else-if="scheduleForm.schedule_type === 'scheduled'">
              实例将在指定时间自动执行
            </span>
            <span v-else-if="scheduleForm.schedule_type === 'dependent'">
              当所有依赖实例完成后，此实例将自动执行
            </span>
          </div>
        </el-form-item>

        <!-- 定时执行配置 -->
        <el-form-item v-if="scheduleForm.schedule_type === 'scheduled'" label="执行时间" required>
          <el-date-picker
            v-model="scheduleForm.scheduled_time"
            type="datetime"
            placeholder="选择执行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
          <div class="form-tip">选择未来的时间点，实例将在该时间自动执行</div>
        </el-form-item>

        <!-- 依赖执行配置 -->
        <el-form-item v-if="scheduleForm.schedule_type === 'dependent'" label="依赖实例" required>
          <el-select
            v-model="scheduleForm.dependency_instance_ids"
            multiple
            filterable
            placeholder="选择依赖的实例（可多选）"
            style="width: 100%"
          >
            <el-option
              v-for="instance in filteredAvailableInstances"
              :key="instance.id"
              :value="instance.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex: 1;">#{{ instance.id }} - {{ instance.instance_name }}</span>
                <el-tag :type="getStatusType(instance.status)" size="small" style="margin-left: 8px;">
                  {{ instance.status }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">
            只能选择未完成的实例作为依赖（排除已完成、失败、已取消的实例）。当所有依赖实例完成后，此实例将自动执行。
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="scheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmSchedule" :loading="publishing">
          确认发布
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import { useWorkflowStore } from '@/stores/workflow'
import WorkflowEditor from '@/components/WorkflowEditor/index.vue'
import { useAutoSave } from '@/composables/useAutoSave'

const route = useRoute()
const router = useRouter()
const templateStore = useWorkflowTemplateStore()
const workflowStore = useWorkflowStore()

const editorRef = ref(null)

// 从路由参数中获取实例信息
const instanceInfo = ref({
  template_id: null,
  template_name: '',
  instance_name: '',
  input_params: {},
  trigger_type: 'manual',
  trigger_user: null,
  cron_enabled: false,
  cron_expression: null,
  schedule_type: 'manual', // 可能的值: manual(立即执行), create_only(仅创建), scheduled, dependent, cron
  schedule_config: null,
  created_by: null
})

const workflowData = ref({
  nodes: [],
  edges: []
})

// 调度类型对话框相关状态
const scheduleDialogVisible = ref(false)
const publishing = ref(false)
const availableInstances = ref([])

const scheduleForm = reactive({
  schedule_type: 'manual',
  scheduled_time: null,
  dependency_instance_ids: []
})

// 自动保存/暂存功能
// 合并 instanceInfo 和 workflowData 用于统一暂存
const draftData = computed({
  get() {
    return {
      instanceInfo: instanceInfo.value,
      workflowData: workflowData.value
    }
  },
  set(value) {
    if (value?.instanceInfo) {
      Object.assign(instanceInfo.value, value.instanceInfo)
    }
    if (value?.workflowData) {
      workflowData.value = value.workflowData
    }
  }
})

const draftKey = computed(() => {
  const templateId = instanceInfo.value?.template_id || 'unknown'
  const instanceName = instanceInfo.value?.instance_name || 'unnamed'
  return `draft-instance-${templateId}-${instanceName}`
})

const { clearDraft } = useAutoSave(draftKey.value, draftData, {
  enabled: true,
  onRecover: (recoveredData) => {
    // 静默恢复
    if (recoveredData?.instanceInfo) {
      Object.assign(instanceInfo.value, recoveredData.instanceInfo)
    }
    if (recoveredData?.workflowData) {
      workflowData.value = recoveredData.workflowData
    }
  }
})

// 过滤可用实例 - 只显示未完成的实例
const filteredAvailableInstances = computed(() => {
  const completedStatuses = ['已完成', '失败', '已取消']
  return availableInstances.value.filter(instance =>
    !completedStatuses.includes(instance.status)
  )
})

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '等待中': 'info',
    '已取消': 'warning',
    '未运行': 'info'
  }
  return typeMap[status] || 'info'
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now()
}

// 切换调度类型时清空相关配置
const handleScheduleTypeChange = () => {
  scheduleForm.scheduled_time = null
  scheduleForm.dependency_instance_ids = []
}

// 生成随机节点ID
const generateNodeId = () => {
  const timestamp = Date.now()
  const randomStr = Math.random().toString(36).substring(2, 13)
  return `node_${timestamp}_${randomStr}`
}

// 将后端格式转换为 Vue Flow 格式
const convertFromBackendFormat = (backendDefinition) => {
  if (!backendDefinition || !backendDefinition.nodes) {
    return { nodes: [], edges: [] }
  }

  // 创建旧ID到新ID的映射
  const idMapping = new Map()
  backendDefinition.nodes.forEach(node => {
    idMapping.set(node.id, generateNodeId())
  })

  const edges = []
  const nodePositions = new Map()

  // 第一遍：收集所有节点和边（使用新ID）
  backendDefinition.nodes.forEach((node, index) => {
    const newNodeId = idMapping.get(node.id)

    // 简单的自动布局：水平排列
    const x = 180 + index * 300
    const y = 90
    nodePositions.set(newNodeId, { x, y })

    // 如果节点有 next，创建边
    if (node.next) {
      const nextNodes = Array.isArray(node.next) ? node.next : [node.next]
      nextNodes.forEach(nextId => {
        const newTargetId = idMapping.get(nextId)
        if (newTargetId) {
          edges.push({
            id: `${newNodeId}${newTargetId}`,
            type: 'smoothstep',
            source: newNodeId,
            target: newTargetId,
            animated: true,
            label: '',
            data: {}
          })
        }
      })
    }
  })

  // 第二遍：转换节点格式（使用新ID）
  const nodes = backendDefinition.nodes.map(node => {
    const newNodeId = idMapping.get(node.id)
    const position = nodePositions.get(newNodeId) || { x: 0, y: 0 }
    idMapping.forEach((newId, oldId) => {
      node.config.experimentConfig = node.config.experimentConfig.replaceAll(oldId, newId)
    })
    return {
      id: newNodeId,
      type: node.type,
      position,
      data: {
        label: node.name || node.type,
        config: node.config || {}
      }
    }
  })

  return { nodes, edges }
}

// 将 Vue Flow 格式转换为后端格式
const convertToBackendFormat = (vueFlowData) => {
  if (!vueFlowData || !vueFlowData.nodes) {
    return { nodes: [] }
  }

  const nodes = vueFlowData.nodes.map(node => {
    const nodeNext = []

    // 查找所有从当前节点出发的边
    if (vueFlowData.edges) {
      vueFlowData.edges.forEach(edge => {
        if (edge.source === node.id) {
          nodeNext.push(edge.target)
        }
      })
    }

    return {
      id: node.id,
      type: node.type,
      name: node.data?.label || node.type,
      config: node.data?.config || {},
      next: nodeNext.length === 1 ? nodeNext[0] : (nodeNext.length > 1 ? nodeNext : null)
    }
  })

  return { nodes }
}

const handleSaveInstance = async (data) => {
  if (!instanceInfo.value.instance_name) {
    ElMessage.warning('实例名称不能为空')
    return
  }

  // 加载可用实例列表（用于依赖选择）
  try {
    const instancesData = await workflowStore.fetchWorkflowInstances({
      page: 1,
      page_size: 100,
      include_not_started: true
    })
    availableInstances.value = instancesData.items || []
  } catch (error) {
    console.error('加载实例列表失败:', error)
  }

  // 重置调度表单
  scheduleForm.schedule_type = 'manual'
  scheduleForm.scheduled_time = null
  scheduleForm.dependency_instance_ids = []

  // 弹出调度类型选择对话框
  scheduleDialogVisible.value = true
}

// 确认发布
const handleConfirmSchedule = async () => {
  // 验证调度配置
  if (scheduleForm.schedule_type === 'scheduled' && !scheduleForm.scheduled_time) {
    ElMessage.warning('请选择执行时间')
    return
  }

  if (scheduleForm.schedule_type === 'dependent' && (!scheduleForm.dependency_instance_ids || scheduleForm.dependency_instance_ids.length === 0)) {
    ElMessage.warning('请选择至少一个依赖实例')
    return
  }

  publishing.value = true

  try {
    // 构建调度配置
    let scheduleConfig = null
    if (scheduleForm.schedule_type === 'scheduled') {
      scheduleConfig = {
        scheduled_time: scheduleForm.scheduled_time
      }
    } else if (scheduleForm.schedule_type === 'dependent') {
      scheduleConfig = {
        dependency_instance_ids: scheduleForm.dependency_instance_ids
      }
    }

    // 转换工作流数据为后端格式
    const workflowDefinition = convertToBackendFormat(workflowData.value)

    // 根据调度类型设置 auto_start
    const autoStart = scheduleForm.schedule_type !== 'create_only'

    // 调用API创建实例（包含 workflow_definition_snapshot）
    const payload = {
      template_id: instanceInfo.value.template_id,
      instance_name: instanceInfo.value.instance_name,
      input_params: instanceInfo.value.input_params,
      trigger_type: 'manual',
      trigger_user: instanceInfo.value.trigger_user,
      cron_enabled: false,
      cron_expression: null,
      schedule_type: scheduleForm.schedule_type,
      schedule_config: scheduleConfig,
      workflow_definition_snapshot: workflowDefinition,
      auto_start: autoStart,
      created_by: instanceInfo.value.created_by
    }

    await templateStore.createInstanceFromTemplate(payload)

    // 清除暂存
    clearDraft()

    // 关闭对话框
    scheduleDialogVisible.value = false

    // 根据调度类型显示不同的提示
    if (scheduleForm.schedule_type === 'create_only') {
      ElMessage.success('工作流实例创建成功，状态为"未运行"，请手动点击"运行"按钮启动')
    } else if (scheduleForm.schedule_type === 'manual') {
      ElMessage.success('工作流实例创建成功，已自动进入执行队列（约1分钟内开始执行）')
    } else if (scheduleForm.schedule_type === 'scheduled') {
      ElMessage.success('工作流实例创建成功，将在指定时间自动执行')
    } else if (scheduleForm.schedule_type === 'dependent') {
      ElMessage.success('工作流实例创建成功，等待依赖实例完成后自动执行')
    }

    router.push('/monitoring')
  } catch (error) {
    console.error('发布实例失败:', error)
    ElMessage.error(error.response?.data?.detail || '发布实例失败')
  } finally {
    publishing.value = false
  }
}

const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消吗？未发布的修改将丢失。',
    '确认取消',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning'
    }
  )
    .then(() => {
      router.push('/monitoring')
    })
    .catch(() => {
      // 用户选择继续编辑，不做任何操作
    })
}

onMounted(async () => {
  // 从路由 query 中获取参数
  const query = route.query

  if (!query.template_id) {
    ElMessage.error('缺少模板ID参数')
    router.push('/monitoring')
    return
  }

  try {
    // 解析参数
    instanceInfo.value = {
      template_id: parseInt(query.template_id),
      template_name: query.template_name || '',
      instance_name: query.instance_name || '',
      input_params: query.input_params ? JSON.parse(query.input_params) : {},
      trigger_type: 'manual',
      trigger_user: query.trigger_user || null,
      cron_enabled: false,
      cron_expression: null,
      schedule_type: 'manual',
      schedule_config: null,
      created_by: query.created_by || null
    }

    // 判断是否为复制操作（传递了 source_instance_id）
    const isDuplicate = query.is_duplicate === 'true' && query.source_instance_id

    if (isDuplicate) {
      // 复制操作：从后端数据库获取源实例的 workflow_definition_snapshot
      const { getWorkflowInstanceDetail } = await import('@/api/workflow')
      const sourceInstance = await getWorkflowInstanceDetail(parseInt(query.source_instance_id))
      
      if (sourceInstance.workflow_definition_snapshot) {
        // 将后端格式转换为 Vue Flow 格式
        // workflow_definition_snapshot 是 JSON 字符串，需要解析为对象
        let snapshotDefinition = sourceInstance.workflow_definition_snapshot
        if (typeof snapshotDefinition === 'string') {
          snapshotDefinition = JSON.parse(snapshotDefinition)
        }
        workflowData.value = convertFromBackendFormat(snapshotDefinition)
      } else {
        ElMessage.error('源实例的工作流定义不存在')
        router.push('/monitoring')
      }
    } else {
      // 从模板创建：加载模板的最新工作流定义
      const templateData = await templateStore.fetchTemplateDetail(query.template_id)

      if (templateData.workflow_definition) {
        // 将后端格式转换为 Vue Flow 格式
        workflowData.value = convertFromBackendFormat(templateData.workflow_definition)
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
    router.push('/monitoring')
  }
})
</script>

<style lang="scss" scoped>
.workflow-instance-editor-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);

  .page-header {
    margin-bottom: 16px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
      }
    }
  }

  .basic-info-card {
    margin-bottom: 16px;
  }

  .editor-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    :deep(.el-card__body) {
      flex: 1;
      padding: 0;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
  }
}
</style>
